// API缓存和优化工具
class APICache {
    constructor() {
        this.cache = new Map();
        this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存
    }

    // 生成缓存键
    generateKey(url, options = {}) {
        const method = options.method || 'GET';
        const body = options.body || '';
        return `${method}:${url}:${body}`;
    }

    // 获取缓存数据
    get(key) {
        const cached = this.cache.get(key);
        if (!cached) return null;
        
        if (Date.now() - cached.timestamp > this.cacheTimeout) {
            this.cache.delete(key);
            return null;
        }
        
        return cached.data;
    }

    // 设置缓存数据
    set(key, data) {
        this.cache.set(key, {
            data: data,
            timestamp: Date.now()
        });
    }

    // 清除特定缓存
    clear(pattern) {
        if (pattern) {
            for (const key of this.cache.keys()) {
                if (key.includes(pattern)) {
                    this.cache.delete(key);
                }
            }
        } else {
            this.cache.clear();
        }
    }

    // 优化的fetch方法
    async fetch(url, options = {}) {
        const key = this.generateKey(url, options);
        
        // 对于GET请求，尝试从缓存获取
        if (!options.method || options.method === 'GET') {
            const cached = this.get(key);
            if (cached) {
                return Promise.resolve(cached);
            }
        }

        try {
            const response = await fetch(url, {
                ...options,
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            // 缓存GET请求的结果
            if (!options.method || options.method === 'GET') {
                this.set(key, {
                    ok: response.ok,
                    status: response.status,
                    json: () => Promise.resolve(data)
                });
            }

            return {
                ok: response.ok,
                status: response.status,
                json: () => Promise.resolve(data)
            };
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 批量请求优化
    async batchFetch(requests) {
        const promises = requests.map(req => this.fetch(req.url, req.options));
        return Promise.all(promises);
    }
}

// 全局API缓存实例
window.apiCache = new APICache();

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 导出工具函数
window.debounce = debounce;
window.throttle = throttle;